package com.atguigu.spzx.common.log.aspect;

import com.atguigu.spzx.common.log.annotation.Log;
import com.atguigu.spzx.common.log.service.SysOperLogService;
import com.atguigu.spzx.common.log.util.LogUtil;
import com.atguigu.spzx.model.entity.system.SysOperLog;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * ClassName: LogAspect
 * Package: com.atguigu.spzx.common.log.aspect
 * Description:
 *
 * @Author 刘强
 * @Create 2024/7/8 10:59
 * @Version 1.0com.atguigu.spzx.common.log.aspect.LogAspect
 */
@Aspect
@Component
public class LogAspect {
    @Resource
    private SysOperLogService sysOperLogService;
    // 定义切点
    @Pointcut("@annotation(com.atguigu.spzx.common.log.annotation.Log)")
    public void logPointcut() {
    }

    // 环绕通知
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint proceedingJoinPoint) {
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Log log = signature.getMethod().getAnnotation(Log.class);
        SysOperLog sysOperLog = new SysOperLog();
        LogUtil.beforeHandleLog(log, proceedingJoinPoint, sysOperLog);
        Object returnValue = null;
        try {
            // 目标方法正常执行
            returnValue = proceedingJoinPoint.proceed();
            LogUtil.afterHandlLog(log,returnValue,sysOperLog,0,null);
            sysOperLogService.saveOperLog(sysOperLog);
        } catch (Throwable e) {
            // 目标方法出错了
            LogUtil.afterHandlLog(log,returnValue,sysOperLog,1, e.getMessage());
            e.printStackTrace();
            sysOperLogService.saveOperLog(sysOperLog);
            //抛出捕获的异常信息---> 为了让事务生效 ---> 这儿会导致事务回滚，从而日志记录失败-->让保存日志的方法脱离原事务
            throw new RuntimeException("出错了");
        }

        return returnValue;
    }
}
